package task

import (
	models2 "Gin-Gorm-boke/boke_common/models"
	"context"
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

func Task4ViewCount() {
	fmt.Println("定时任务Task4ViewCount启动")
	viewCountMap, err := models2.RDb.HGetAll(context.Background(), "article:viewCount").Result()
	if err != nil {
		fmt.Println("Redis获取文章浏览量失败")
		return
	}
	for k, v := range viewCountMap {
		articleId, _ := strconv.Atoi(k)
		viewCount, _ := strconv.Atoi(v)
		if viewCount != 0 {
			fmt.Println("文章id:" + strconv.Itoa(articleId))
			models2.Db.Model(new(models2.Article)).
				Where("id=?", articleId).
				Update("view_count", gorm.Expr("view_count+?", viewCount))
		}
		models2.RDb.HDel(context.Background(), "article:viewCount", k)

	}

}
